//
//  WHCoopExpressController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/6.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHCoopExpressController.h"
#import "WHCoopExpressInfoCell.h"
#import "WHNoDataViewTool.h"
#import "WHCoopExpressHeaderView.h"
#import "WHCoopRequestListController.h"
#import "PPBadgeView.h" // 消息管理

@interface WHCoopExpressController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, assign) BOOL isF;

@end

@implementation WHCoopExpressController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self isNumber];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"合作快递";
    
    [self initParams];
    [self setUpNavigationItem];
    [self setUpTableView];
    [self headerRereshing];
}

- (void)initParams {
    _page = 1;
    _dataArray = @[].mutableCopy;
}

- (void)setUpNavigationItem {
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightButton.frame = CGRectMake(0, 0, 80, kNavBarHeight);
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:@"申请列表" attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(16)), NSForegroundColorAttributeName:CMDarkOrangeColor}];
    [rightButton setAttributedTitle:attStr forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [rightButton addTarget:self action:@selector(requestList:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [rightButton pp_addDotWithColor:nil];
    [rightButton pp_moveBadgeWithX:0 Y:9];
    _rightButton = rightButton;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[WHCoopExpressInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHCoopExpressInfoCell class])];
    
    dataTableView.tableFooterView = [UIView new];
    dataTableView.backgroundColor = KClearColor;
    dataTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.equalTo(@kTopHeight);
    }];
    
    kWeakSelf(self);
    dataTableView.mj_header = [WHGifHeader headerWithRefreshingBlock:^{
        [weakself headerRereshing];
    }];
    
    dataTableView.mj_footer = [WHGifFooter footerWithRefreshingBlock:^{
        [weakself footerRereshing];
    }];
    dataTableView.mj_footer.hidden = YES;
    
    _dataTableView = dataTableView;
}

- (void)showNoDataView {
    self.dataTableView.tableFooterView = [self noMoreDataFooterView];
}

- (void)hideNoDataView {
    self.dataTableView.tableFooterView = [UIView new];
}

- (UIView *)noMoreDataFooterView {
    UIView *tableFootView = [[UIView alloc] init];
    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, kScreenHeight - kTopHeight - kRealwidth(35));
    
    [WHNoDataViewTool addNodataViewAt:tableFootView imageName:@"png_nodataView" tipsLabelText:@"暂无数据" tapAction:nil];
    
    return tableFootView;
}

- (void)headerRereshing {
    [self getCoopListByPageNumber:1 completion:^(BOOL isSucess, BOOL isLast) {
        [self.dataTableView.mj_header endRefreshing];
        if (isSucess) {
            _page = 1;
            self.dataTableView.mj_footer.hidden = NO;
            if (isLast) {
                self.dataTableView.mj_footer.hidden = YES;
            } else {
                [self.dataTableView.mj_footer resetNoMoreData];
            }
        }
    }];
}

- (void)footerRereshing {
    [self getCoopListByPageNumber:(_page+1) completion:^(BOOL isSucess, BOOL isLast) {
        if (isSucess) {
            if (isLast) {
                [self.dataTableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                _page = _page + 1;
                [self.dataTableView.mj_footer endRefreshing];
            }
            
        } else {
            [self.dataTableView.mj_footer endRefreshing];
        }
        
    }];
    
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHCoopExpressInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHCoopExpressInfoCell class]) forIndexPath:indexPath];
    WHStationNameModel *nameModel = self.dataArray[indexPath.row];
    cell.nameModel = nameModel;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(35);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    WHCoopExpressHeaderView *header = [[WHCoopExpressHeaderView alloc] init];
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kRealwidth(35);
}

#pragma mark - —————— 事件 ——————

- (void)requestList:(UIButton *)button {
    WHCoopRequestListController *list = [[WHCoopRequestListController alloc] init];
    [self.navigationController pushViewController:list animated:YES];
}

#pragma mark - —————— 接口 ——————
- (void)getCoopListByPageNumber:(int)pageNumber completion:(void (^)(BOOL isSucess, BOOL isLast))completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_selectList);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          @(pageNumber), @"pageNum",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                NSDictionary *object = responseObject[@"retobj"];
                
                if (pageNumber == 1) {
                    [_dataArray removeAllObjects];
                }
                
                NSArray *stations = object[@"data"];
                if (stations.count == 0) {
                    if (completion) {
                        [self.dataTableView reloadData];
                        completion(YES, YES);
                    }
                    if (pageNumber == 1) {
                        DLog(@"没有数据");
                        [self showNoDataView];
                    }
                    return;
                }
                [self hideNoDataView];
                
                NSArray *tempStationArray = [NSArray modelArrayWithClass:[WHStationNameModel class] json:stations];
                [self.dataArray addObjectsFromArray:tempStationArray];
                [self.dataTableView reloadData];
                
                if (completion) {
                    completion(YES, NO);
                }
                
            } else {
                [WHView showMessage:errorMsg inView:self.view];
                if (completion) {
                    completion(NO, NO);
                }
            }
        }
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO, NO);
        }
    }];
}

- (void)isNumber {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_isnumber);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@(userManager.detailUserInfo.userId), @"userId", nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSNumber *retObj = responseObject[@"retobj"];                
                if (retObj.boolValue) {
                    [_rightButton pp_showBadge];
                } else {
                    [_rightButton pp_hiddenBadge];
                }
                
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

@end
